package tgc.edu.exam.web.controller;

import java.util.HashSet;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.exam.custom.CommonController;
import tgc.edu.exam.entity.ArticleManagement;
import tgc.edu.exam.service.ArticleManagementService;
import tgc.edu.exam.web.form.ArticleManagementForm;

@Controller
@RequestMapping(value="/articleManagement")
public class ArticleManagementController extends CommonController<ArticleManagement, UUID, ArticleManagementForm> {
	@Autowired
	private ArticleManagementService aService;
	
	@RequestMapping(value="/visit")
	@ResponseBody
	public Object visit(String id) {
		return aService.findById(UUID.fromString(id)).getContent();
	}
	
	@Override
	public Specification<ArticleManagement> buildSpec(ArticleManagementForm form) {
		Specification<ArticleManagement> specification = new Specification<ArticleManagement>() {

			private static final long serialVersionUID = 1L;
			
			@Override
			public Predicate toPredicate(Root<ArticleManagement> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				if(StringUtils.hasText(form.getTitle())) {
					Predicate name = cb.like(root.get("title"), "%"+form.getTitle()+"%");
					rules.add(name);
				}
				if(StringUtils.hasText(form.getType())) {
					Predicate difficultylevel = cb.like(root.get("type"), "%"+form.getType()+"%");
					rules.add(difficultylevel);
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}

		};
		return specification;
	}
}
